#define _CRT_SECURE_NO_WARNINGS 1
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool dfs(TreeNode* root)
    {
        if (root->left == nullptr)
        {
            return root->val == 0 ? false : true;
        }
        bool left = dfs(root->left);
        bool right = dfs(root->right);
        // if(root->val  == 2)
        //     return left | right;
        // else 
        //     return left & right;
        return root->val == 2 ? left | right : left & right;
    }
    bool evaluateTree(TreeNode* root) {
        return dfs(root);
    }
};


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
 // class Solution {
 // public:
 //     int dfs(TreeNode* root, int subsum)
 //     {
 //         if(root == nullptr)
 //             return 0;
 //         int prevsum = subsum*10 + root->val;
 //         if(root->left == nullptr && root->right == nullptr)
 //             return prevsum;
 //         int left = dfs(root->left,prevsum);
 //         int right = dfs(root->right,prevsum);
 //         return left + right;
 //     }
 //     int sumNumbers(TreeNode* root) {
 //         return dfs(root, 0);
 //     }
 // };

class Solution {
public:
    int dfs(TreeNode* root, int prevsum)
    {
        prevsum = prevsum * 10 + root->val;
        if (root->left == nullptr && root->right == nullptr)
            return prevsum;
        int ret = 0;
        if (root->left)  ret += dfs(root->left, prevsum);
        if (root->right) ret += dfs(root->right, prevsum);
        return ret;
    }
    int sumNumbers(TreeNode* root) {
        return dfs(root, 0);
    }
};


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* pruneTree(TreeNode* root) {
        if (root == nullptr)
            return nullptr;
        root->left = pruneTree(root->left);
        root->right = pruneTree(root->right);
        if (root->left == nullptr && root->right == nullptr && root->val == 0)
            return nullptr;
        else
            return root;

    }
};